/**
* Main.js controlador principal para la vista mainContainer,menuUser00,loginForm,menuUser01,menuUser02,regionesList, charts.
* Aqui se declaran los eventos utilizados
* en el aplicativo.
*/
Ext.define("entgpv11.controller.Main", {
    extend: "Ext.app.Controller",
    config:
    {
        refs:
        {
            menuUser00: "menuuser00",
            mainContainer: "maincontainer",
            menuUser01: "menuuser01",
            loginForm: "login",
            menuUser02: "menuuser02",
            regionesList: "regioneslistcontainer",
            charts: "regionescharts",
            usgsMap: "usgsmap"
        },
        control:
        {
            mainContainer:
            {
                exitCommand: "onExitCommand"

            },
            menuUser00:
            {
                backButtonTapCommand: "onExitButtonTapCommand"
            },
            loginForm:
            {
                loginCommand: "onLoginCommand"
            },
            menuUser01:
            {
                backButtonTapCommand: "onExitButtonTapCommand",
                btnSeekCommand: "onBtnSeekCommand"
            },
            menuUser02:
            {
                backToHomeCommand: "onExitButtonTapCommand",
                exitButtonTapCommand: "onExitButtonTapCommand"
            },
            regionesList:
            {
                editRegionesCommand: "onEditRegionesCommand"
            },
            charts:
			{
			    backButtonMenu02Command: "onBackButtonMenu02Command",
			    exitButtonTapCommand: "onExitButtonTapCommand"
			}
        }
    },
    // Transitions
    slideLeftTransition: { type: 'slide', direction: 'left' },
    // Helper functions
    loadJS: function (id, src) {
        if (document.getElementById(id) != null) return;
        var js = document.createElement('script');
        js.id = id; js.async = false; js.src = Ext.require.moduleUrl + src; js.type = 'text / javascript';
        document.getElementsByTagName('head')[0].appendChild(js);
    },
    /**
    * Recupera los datos del usuario para autetificarlo
    * @loginForm
    * @btnLogin
    */
    ajaxRequest: function (loginForm, btnLogin) {
        try {
           
            loginForm.setMasked({
                xtype: 'loadmask',
                message: 'Cargando..'
            });
            // Extend timeout for all Ext.Ajax.requests to 90 seconds.  
            // Ext.Ajax is a singleton, this statement will extend the timeout  
            // for all subsequent Ext.Ajax calls.  
            Ext.Ajax.timeout = 90000;  
  
            Ext.Ajax.request({
                url: APP_GLOBAL.getServiceUrl() + "GetLogin",
                disableCaching: false,
                scriptTag: true,
                method: 'POST',
                params: loginForm.getValues(),
                scope: this,
                failure: function (response, opts) {
                    btnLogin.enable();
                    loginForm.unmask();
                    Ext.Msg.alert("Error con la Red");
                    throw ('GetLogin ' + response.status);

                },
                success: function (response, opts) {

                    var rObject = Ext.decode(response.responseText);
                    var bFlag = new Boolean(false);
                    if (rObject.user.length != 0) {
                        if (rObject.user[0].Status == "1") {
                            bFlag = new Boolean(true);
                        }
                    }
                    loginForm.unmask();
                    if (bFlag == false) {
                        btnLogin.enable();
                        loginForm.reset();
                        Ext.Msg.alert("Usuario Incorrecto");
                    }
                    else {
                        var formNext = {
                            xtype: "menuuser00",
                            dataId: rObject.user[0].IdEmp
                        };

                        switch (rObject.user[0].CRol) {
                            case "ADM":
                                formNext = {
                                    xtype: "menuuser01",
                                    dataId: rObject.user[0].IdEmp,
                                    rol: rObject.user[0].CRol
                                };
                                break;
                            case "RAF":
                                formNext = {
                                    xtype: "menuuser02",
                                    dataId: rObject.user[0].IdEmp,
                                    rol: rObject.user[0].CRol
                                };
                                break;

                        }
                        btnLogin.enable();
                        loginForm.reset();
                        Ext.Viewport.animateActiveItem(formNext, this.slideLeftTransition);

                    }
                }
            });
        } catch (ex) {
            APP_GLOBAL.SetLog('ajaxRequest::' + ex);
        }
    },
    // Commands.
    /**
    *        
    *   MAINCONTAINER:
    *   {
    *       exitCommand: "onExitCommand"
    *   } 
    *        
    */
    /**
    * Test
    * @tabBar
    * @newTab
    * @oldTab
    * @type
    */
    onExitCommand: function (tabBar, newTab, oldTab, type) {
        try {

            var index = tabBar.indexOf(newTab);
            if (index == 4) {

                switch (type) {
                    case 1:
                        if (typeof window.onunload === "function")
                            window.onunload();
                        if (typeof blackberry.app.exit === "function")
                            blackberry.app.exit();
                        break;
                    case 2:
                        if (typeof NativeApplication.nativeApplication.exit === "function")
                            NativeApplication.nativeApplication.exit();
                        break;
                    case 3:
                        if (typeof device.exitApp === "function")
                            device.exitApp()
                        break;

                } // switch

            } //if
        } catch (ex) {
            APP_GLOBAL.SetLog('onExitCommand::' + type + ' ' + ex);
        }

    },

    /**
    *    MENUUSER00:
    *            {
    *                backButtonTapCommand: "onExitButtonTapCommand"
    *            }
    */
   
    /**
    * 
    * Evento para salir y mostrar la interfaz inicial
    *
    */
    onExitButtonTapCommand: function () {
        try {
            //Ext.getCmp('firenewsitems').destroy();
            Ext.Viewport.animateActiveItem(this.getMainContainer(), this.slideLeftTransition);
        } catch (ex) {
            APP_GLOBAL.SetLog('onExitButtonTapCommand::' + ex);
        }

    },
    
    /**
    *            LOGINFORM:
    *            {
    *                loginCommand: "onLoginCommand"
    *            }

    */
    /**
    * Evento para la auteficacion de usuario
    * 
    * 
    */
    onLoginCommand: function () {
        try {
            var btnLogin = Ext.getCmp("btnLogin");
            var loginForm = this.getLoginForm();
            var loginModel = Ext.create('entgpv11.model.Login'), errors, errorMessage = '';
            btnLogin.disable();
            loginForm.updateRecord(loginModel);
            errors = loginModel.validate();

            if (!errors.isValid()) {
                loginForm.reset();
                btnLogin.enable();
                errors.each(function (err) {
                    errorMessage += err.getMessage() + '<br/>';
                }); // each()
                Ext.Msg.alert('Error', errorMessage);
            }
            else {
                this.ajaxRequest(loginForm, btnLogin);
            } // if

        } catch (ex) {
            APP_GLOBAL.SetLog(' onLoginCommand::' + ex);
        }

    },
    /**
    *           
    * MENUUSER01:
    *            {
    *                backButtonTapCommand: "onExitButtonTapCommand",
    *                btnSeekCommand: "onBtnSeekCommand"
    *            }
    */
    /**
    * Activa el viewport con la  interfaz de listado de proyectos
    * @me
    * 
    */
    onBtnSeekCommand: function (me) {
        try {
            var form = this.getMenuUser01(), values = form.getValues();
            var formNext = {
                xtype: "notescontainer",
                dataArguments: values,
                rol: me.getRol()
            };
            //this.loadJS('maps', 'http://maps.google.com/maps/api/js?sensor=true');
            Ext.Viewport.animateActiveItem(formNext, this.slideLeftTransition);
        } catch (ex) {
            APP_GLOBAL.SetLog('onBtnSeekCommand::' + ex);
        }
    },

    /**           
    *   MENUUSER02:
    *            {
    *                backToHomeCommand: "onExitButtonTapCommand",
    *                exitButtonTapCommand: "onExitButtonTapCommand"
    *            }

    */
    //Reutilizados
    /**           
    *   REGIONESLIST:
    *            {
    *                editRegionesCommand: "onEditRegionesCommand"
    *            }
    */

    /**
    * Muestra la interfaz de listado de regiones
    * @list
    * @record
    */
    onEditRegionesCommand: function (list, record) {
        try {
            var formNext = {
                xtype: "regionescharts",
                dataArguments: record
            };
            Ext.Viewport.animateActiveItem(formNext, this.slideLeftTransition);
        } catch (ex) {
            APP_GLOBAL.SetLog('onEditRegionesCommand::' + ex);
        }
    },

    /**            
    *   CHARTS:
    *			{
    *			    backButtonMenu02Command: "onBackButtonMenu02Command",
    *			    exitButtonTapCommand: "onExitButtonTapCommand"
    *			}
    */
 
    /**
    * Muestra la interfaz relacionada con el perfil 2 del usuario
    * 
    * 
    */
    onBackButtonMenu02Command: function () {
        try {
            Ext.Viewport.animateActiveItem(this.getMenuUser02(), this.slideLeftTransition);
        } catch (ex) {
            APP_GLOBAL.SetLog('onBackButtonMenu02Command::' + ex);
        }

    },
   
    // Base Class functions.
    launch: function () {
        this.callParent(arguments);
    },
    init: function () {
        this.callParent(arguments);
    }
});